package com.learn.english.controller;

import com.learn.english.domain.R;
import com.learn.english.model.entity.Course;
import com.learn.english.model.ro.CourseRo;
import com.learn.english.service.ICourseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.Date;
import org.springframework.beans.factory.annotation.Value;

/**
 * 课程控制器
 * 
 * @author TISNIW
 * @version 1.0
 */
@RestController
@RequestMapping("/course")
@RequiredArgsConstructor
@Slf4j
public class CourseController {
    @Autowired
    private ICourseService courseService;
    
    @Value("${path.user.file_url}")
    private String filePath;

    /**
     * 分页获取课程列表
     *
     * @param pageNum  当前页码
     * @param pageSize 每页数量
     * @param name     课程名称（可选，模糊查询）
     * @return 分页数据
     */
    @GetMapping("/list")
    public R<List<CourseRo>> getCourseList(
            @RequestParam(defaultValue = "0") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name) {
        log.info("pageNum:{}", pageNum);
        log.info("pageSize:{}", pageSize);
        List<CourseRo> result = courseService.page(pageNum, pageSize, name);
        log.info("result:{}", result);
        return R.ok(result);
    }

    /**
     * 获取课程总页数
     * 
     * @param pageSize 每页数量
     * @return 总页数
     */
    @GetMapping("/page-count")
    public R<Long> getCoursePageCount(@RequestParam(defaultValue = "10") Integer pageSize) {
        return R.ok(courseService.getPage(pageSize));
    }

    /**
     * 获取课程详情
     *
     * @param courseId 课程ID
     * @return 课程对象
     */
    @GetMapping("/info/detail")
    public R<Course> getCourseDetail(@RequestParam Long courseId) {
        Course course = courseService.getById(courseId);
        if (course == null) {
            return R.fail(404, "课程不存在");
        }
        return R.ok(course);
    }
    
    /**
     * 获取课程详情（兼容旧接口）
     *
     * @param id 课程ID
     * @return 课程对象
     */
    @GetMapping("/get/{id}")
    public R<Course> getCourseById(@PathVariable Long id) {
        Course course = courseService.getById(id);
        if (course == null) {
            return R.fail(404, "课程不存在");
        }
        return R.ok(course);
    }

    /**
     * 添加课程（支持文件上传）
     *
     * @param courseName 课程名称
     * @param courseDesc 课程描述
     * @param file 课程封面文件
     * @return 响应结果
     */
    @PostMapping("/add")
    public R<Course> addCourse(@RequestParam String courseName,
                             @RequestParam String courseDesc,
                             @RequestParam(required = false) MultipartFile file) {
        try {
            log.info("开始处理课程上传请求：课程名称={}", courseName);
            
            // 创建课程对象并设置必填字段
            Course course = new Course();
            course.setName(courseName);
            course.setDesc(courseDesc);
            
            // 设置默认值
            course.setCategoryId(1); // 默认分类ID
            course.setTeacherId(1); // 默认教师ID
            course.setIsFree(true); // 默认免费
            course.setCost(BigDecimal.ZERO); // 默认价格0
            course.setCount(0L); // 默认观看人数0
            course.setCreatedAt(LocalDateTime.now());
            course.setUpdatedAt(LocalDateTime.now());
            
            // 处理文件上传
            if (file != null && !file.isEmpty()) {
                log.info("收到文件上传：文件名={}, 大小={}KB", 
                         file.getOriginalFilename(), 
                         file.getSize() / 1024);
                
                // 生成唯一文件名
                String extension = StringUtils.getFilenameExtension(file.getOriginalFilename());
                String fileName = UUID.randomUUID() + (extension != null ? "." + extension : ".jpg");
                
                // 文件保存路径
                String saveDir = filePath + "/courses/";
                String fileRelativePath = "courses/" + fileName;
                
                try {
                    // 确保目录存在
                    Path dirPath = java.nio.file.Paths.get(saveDir);
                    if (!Files.exists(dirPath)) {
                        Files.createDirectories(dirPath);
                    }
                    
                    // 保存文件到磁盘
                    Path targetPath = dirPath.resolve(fileName);
                    Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
                    
                    // 设置封面URL
                    course.setCoverUrl("/file/get/image?url=" + fileRelativePath);
                    log.info("文件上传成功，保存路径：{}", fileRelativePath);
                } catch (IOException e) {
                    log.error("文件保存失败", e);
                    return R.fail(500, "文件上传失败：" + e.getMessage());
                }
            }
            long timestamp = System.currentTimeMillis();
            int courseId = (int) (timestamp % Integer.MAX_VALUE);
            course.setId(courseId);
            course.setCourseUrl("/course/" + courseId);
            // 保存课程到数据库
            if (courseService.saveById(course)) {
                log.info("课程添加成功：课程ID={}", course.getId());
                return R.ok(course);
            } else {
                log.error("课程保存到数据库失败");
                return R.fail(500, "课程添加失败");
            }
        } catch (Exception e) {
            log.error("添加课程时发生异常", e);
            return R.fail(500, "课程添加失败：" + e.getMessage());
        }
    }

    /**
     * 更新课程信息
     *
     * @param id     课程ID
     * @param course 新的课程数据
     * @return 成功/失败
     */
    @PostMapping("/update/{id}")
    public R<Boolean> updateCourse(@PathVariable Long id, @RequestBody Course course) {
        if (!courseService.exists(id)) {
            return R.fail(404, "课程不存在");
        }

        course.setId(Math.toIntExact(id));
        course.setUpdatedAt(LocalDateTime.now());

        boolean ok = courseService.updateById(course);
        return ok ? R.ok(true) : R.fail(404, "更新失败");
    }

    /**
     * 删除课程
     *
     * @param courseId 课程ID
     * @return 响应结果
     */
    @PostMapping("/delete")
    public R<Boolean> deleteCourse(@RequestParam Long courseId) {
        boolean remove = courseService.removeById(courseId);
        if (remove) {
            return R.ok(true);
        }
        return R.fail(404, "删除课程失败");
    }
    
    /**
     * 删除课程（兼容旧接口）
     *
     * @param id 课程ID
     * @return 响应结果
     */
    @DeleteMapping("/delete/{id}")
    public R<Boolean> deleteCourseOld(@PathVariable Long id) {
        boolean remove = courseService.removeById(id);
        if (remove) {
            return R.ok(true);
        }
        return R.fail(404, "删除课程失败");
    }
}
